<template>
  <div class="biz-container">
    <table-layout
      :haveSider="false"
      :isStandTable="false"
    >
      <template #headCustom>
        <a-button
          type="primary"
          @click="onBack"
        >返回</a-button>
        <a-button
          type="primary"
          style="marginLeft:20px"
          @click="toSubmit"
        > 提交 </a-button>
      </template>
      <template #form>
        <div class="card">
          <div class="viewTitle">
            {{btn[0].name}}
            <a-button
              type="link"
              class="upAndDown"
              @click="upAndDown($event,0)"
            >
              <a-icon
                v-if="btn[0].isUp"
                type="up"
              />
              <a-icon
                v-else
                type="down"
              />
            </a-button>
          </div>
          <merge-step3 ref="orderInfo" v-if="isExit"  @onSubmitForm="onSubmitForm" v-show="btn[0].isUp" ></merge-step3>
        </div>
        <div class="dis"></div>
        <div class="card">
          <div class="viewTitle">
            {{btn[1].name}}
            <a-button
              type="link"
              class="upAndDown"
              @click="upAndDown($event,1)"
            >
              <a-icon
                v-if="btn[1].isUp"
                type="up"
              />
              <a-icon
                v-else
                type="down"
              />
            </a-button>
          </div>
          <merge-step1 ref="orderDetail" v-if="isExit" @onNextStep="onSubmitDetail" v-show="btn[1].isUp" :detailData="listdata"></merge-step1>
        </div>
        <div class="dis"></div>
        <div class="card">
          <div class="viewTitle">
            {{btn[2].name}}
            <a-button
              type="link"
              class="upAndDown"
              @click="upAndDown($event,2)"
            >
              <a-icon
                v-if="btn[2].isUp"
                type="up"
              />
              <a-icon
                v-else
                type="down"
              />
            </a-button>
          </div>
          <merge-step2 ref="invoices" v-if="isExit" v-show="btn[2].isUp"></merge-step2>
        </div>
      </template>
    </table-layout>
  </div>
</template>

<script>
import {
  getMergeByConditions,
  checkDetailNum,
  saveMerge
} from './saleDelivery'

import tableLayout from '@/views/app/biz/common/index'
import mergeStep1 from './mergeStep1.vue'
import mergeStep2 from './mergeStep2.vue'
import mergeStep3 from './mergeStep3.vue'
import mergeStep4 from './mergeStep4.vue'
import storage from 'store'
export default {
  components: {
    tableLayout,
    mergeStep1,
    mergeStep2,
    mergeStep3,
    mergeStep4
  },
  data() {
    return {
      btn: [
        { name: '配送单信息', isUp: true },
        { name: '配送单明细', isUp: true },
        { name: '发票信息', isUp: true }
      ],
      conditions: [],
      pagination: {
        current: 1, //当前页码 current
        pageSize: 100000, //每页显示条数 pageSize
        total: 1,
      },
      listdata:[],
      isExit:true,
      backPathName:'undeliveredOrder',
      submitData: {
        deliveryOrder: {},
        deliveryOrderDetails: [],
        invoices: []
      }
    }
  },
  computed: {},
  beforeRouteEnter(to,from,next){
    next((vm=>{
      vm.conditions=to.params.goodsId
    }))
  },
  mounted(){
    //刷新页面时读取缓存
    if (!this.$route.params.goodsId) {
      this.conditions = storage.get('goodsId')? storage.get('goodsId'):[]
      this.setParams()
      console.log(storage.get('goodsId'));
    }
  },
  activated(){
    console.log('activated',this.$route,this.$route.params.goodsId );
    //如果传了值表示为重新点击进去的，需要初始化数据，如果未传值表示缓存在页签中，需路由配置keepAlive
    if (this.$route.params.goodsId) {
      this.initData()
      this.backPathName = this.$route.params.pathName ? this.$route.params.pathName : this.backPathName
      this.conditions = this.$route.params.goodsId
      storage.set('goodsId',this.conditions)
      this.setParams()
    } 
  },
  methods: {
    initData(){
      console.log('重置数据');
      Object.assign(this.$data, this.$options.data.call(this))
      this.isExit=false
      setTimeout(()=>{
        this.isExit=true
      },1)
    },
    setParams(){
      console.log('conditions', this.conditions)
      let condition=''
      for (const item of this.conditions) {
        condition=condition+item.saleOrderNo+','
      }
      // this.getTotal()
      const pa = {
        'saleOrders': condition
      }
      this.getList(pa)
    },
    upAndDown (e, num) {
      if (this.btn[num].isUp) {
        this.btn[num].isUp = false
      } else {
        this.btn[num].isUp = true
      }
    },
    onBack () {
      this.$router.push({
        name: this.backPathName,
        params: {
          isJump: false,
          pathName: this.$route.name,
          iscloseMul:true,
        }
      })
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn=['删除']
      this.listdata=[]
      let res = ''
      res = await getMergeByConditions(params,this.pagination)
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        for (let id in resdata) {
          for (const item of resdata[id].child) {
            item.iunitprice=item.iunitprice.toFixed(2)
            item.key=item.pid
            item.execNum=item.execNum?item.execNum:null
            item.batchCode=item.batchCode?item.batchCode:null
            item.productDate=item.productDate?item.productDate:null
            item.expiryDate=item.expiryDate?item.expiryDate:null
            item.action=['添加','删除']
          }
          this.listdata.push({
            key: id,
            action:actionBtn,
            selectedRowKeys:[],
            child:resdata[id].child?resdata[id].child:[],
            ...resdata[id].saleOrderDetail,

          })
        }
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
      this.$refs.orderInfo.setformDatas(this.listdata)
    },
    
    toSubmit() {
      //检查表单是否填写
      this.$refs.orderInfo.onValidate()
    },
    onSubmitForm(){
      //检查明细是否正确
      this.$refs.orderDetail.onNext()
    },
    onSubmitDetail(){
      this.submitData.deliveryOrderDetails = this.$refs.orderDetail.listdata
      this.submitData.invoices = this.$refs.invoices.listdata
      this.submitData.deliveryOrder =this.$refs.orderInfo.s_formDatas
      console.log('提交', this.submitData)
      if (!this.submitData.deliveryOrderDetails.length) {
        this.$message.warning({content:'没有商品明细'})
        return
      }
      this.saveMerge(this.submitData)
    },
    // 保存信息
    async saveMerge(val) {
      console.log(val);
      let key = 'updatable'
      this.$message.loading({ content: '提交中',key })
      let res = await saveMerge(val)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1') {
        this.$message.success({ content: '提交成功',key, duration: 2 })
        this.$store.state.deliverOrder=this.submitData
        setTimeout(()=>{
          this.onBack()
        },1000)
      } else {
        this.$message.success({ content: '提交失败,请稍后再试',key, duration: 2 })
      }
    }
  }
}
</script>

<style></style>
